<template>
  <view class="order-info">
    <!-- 订单状态和倒计时 -->
    <view class="status-box">
      <view class="status-header">
        <text class="status-text" :class="getStatusClass(info.paymentStatus)">
          {{ getStatusText(info.paymentStatus) }}
        </text>
        <view class="countdown" v-if="info.paymentStatus === 0">
          <text class="countdown-label">支付倒计时：</text>
          <text class="countdown-time" :class="{'countdown-warning': countdown.isNearTimeout}">
            {{ countdown.text }}
          </text>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-card">
      <view class="card-info">
        <view class="card-info-left">
          <view class="card-info-title">
            <text class="card-info-h1">{{ info.courseName }}</text>
            <text class="tag">初训</text>
          </view>
          <view class="card-info-txt">
            <view class="iconfont icon-weikaishi1"></view>
            <text>上课时间：48课时 09:00-18:00</text>
          </view>
          <view class="card-info-txt">
            <view class="iconfont icon-dingwei"></view>
            <text>中山市企安校区</text>
          </view>
        </view>
        <text class="price">¥{{ info.totalAmount }}</text>
      </view>
    </view>

    <!-- 订单详情 -->
    <view class="order-card" style="padding: 30rpx 30rpx 0rpx 30rpx;">
      <view class="order-card-list">
        <text class="first">订单编号：</text>
        <text>{{ info.orderId }}</text>
      </view>
      <view class="order-card-list">
        <text class="first">购买时间：</text>
        <text>{{ parseTime(info.orderDate) }}</text>
      </view>
      <view class="order-card-list">
        <text class="first">支付方式：</text>
        <text>{{ info.paymentMethod }}</text>
      </view>
      <view class="order-card-list" v-if="info.payDate">
        <text class="first">支付时间：</text>
        <text>{{ parseTime(info.payDate) }}</text>
      </view>
    </view>
    <view class="sale">
        <text>优惠信息</text>
        <view class="sale-txt">
          优惠:<text>暂无</text>
        </view>
      </view>
      <view class="total">
        <text style="margin-right: 8rpx;">共计1门课程，小计</text>
        <text style="font-size: 28rpx;color: #2A2C31;font-weight: 700;">¥</text>
        <text class="num">{{  info.totalAmount  }}</text>
      </view>
    <!-- 底部按钮 -->
    <view class="bottom-btns" v-if="info.paymentStatus === 0 && !isTimeout">
      <button class="btn-cancel" @click="cancelOrder">取消订单</button>
      <button class="btn-pay" @click="payOrder">立即支付</button>
    </view>
    <view class="bottom-btns" v-if="info.paymentStatus === 1 ">
      <button class="btn-pay" @click="refund">申请退款</button>
    </view>

    <!-- 添加退款弹窗 -->
    <uv-popup ref="showRefundPopup" @close="closeRefundPopup" mode="center">
      <view class="refund-popup">
        <view class="popup-header">
          <text class="title">申请退款</text>
          <text class="close" @click="closeRefundPopup">×</text>
        </view>
        
        <uv-form 
          :model="refundForm" 
          :rules="rules"
          ref="refundForm" 
          labelWidth="160rpx"
          borderBottom
        >
          <uv-form-item label="课程名称">
            <text>{{ info.courseName }}</text>
          </uv-form-item>
          
          <uv-form-item label="订单金额">
            <text>¥{{ info.totalAmount }}</text>
          </uv-form-item>
          
          <uv-form-item label="退款金额">
            <text>¥{{ info.totalAmount }}</text>
          </uv-form-item>
          
          <uv-form-item label="订单时间">
            <text>{{ parseTime(info.orderDate) }}</text>
          </uv-form-item>
          
          <uv-form-item label="支付时间">
            <text>{{ parseTime(info.payDate) }}</text>
          </uv-form-item>
          
          <uv-form-item 
            label="退款原因" 
            prop="remark" 
            :rules="[{ required: true, message: '请输入退款原因' }]"
          >
            <uv-textarea
              v-model="refundForm.remark"
              placeholder="请输入退款原因"
              :maxlength="200"
            />
          </uv-form-item>
        </uv-form>
        
        <view class="popup-footer">
          <button class="btn-cancel" @click="closeRefundPopup">取消</button>
          <button class="btn-confirm" @click="submitRefund">确认申请</button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import { getOrderDetail, cancelOrder, orderRefund } from '@/http/order.js'
import { parseTime } from '@/utils/tools.js'
import {
  placeOrder,
  payOrderWithWXPay
} from '@/http/exam.js'
export default {
  data() {
    return {
      info: {
        course: null,
        courseId: '',
        courseName: '',
        oldAmount: 0,
        orderDate: 0,
        orderId: '',
        payDate: null,
        paymentMethod: '',
        paymentStatus: 0,
        refund: null,
        teacherId: 0,
        timeOut: 0,
        totalAmount: 0,
        userId: 0
      },
      userinfo: {},
      countdown: {
        text: '',
        isNearTimeout: false
      },
      timer: null,
      isTimeout: false,
      refundOrder: {
        courseName: "string", // 课程名称  display true
        orderDate: "2024-11-25T07:09:44.484Z", // 订单日期  display true
        payDate: "2024-11-25T07:09:44.484Z", // 支付日期  display true
        orderId: "string", // 订单id  display true
        refundAmount: 0, // 退款金额  display true
        remark: "string",  // 退款原因  display fasle
        status: 0, // 退款状态  display true
        totalAmount: 0, // 订单金额  display true
        paymentMethod: 0, // 支付方式  display true 
        updateTime: "2024-11-25T07:09:44.484Z", // 更新时间  display true
        userId: 0 // 用户id  display true 
      },
      showRefundPopup: false,
      refundForm: {
        orderId: '',
        refundAmount: 0,
        remark: ''
      },
      rules: {
        remark: [{
          required: true,
          message: '请输入退款原因',
          trigger: ['blur', 'change']
        }]
      }
    }
  },
  methods: {
    parseTime,
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        4: '已退款',
        5: '退款申请中'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        0: 'status-pending',
        1: 'status-paid',
        2: 'status-cancelled',
        4: 'status-refunded'
      }
      return classMap[status]
    },
    cancelOrder() {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            cancelOrder({
              orderId: this.info.orderId
            }).then(res => {
              uni.showToast({
                title: '取消成功',
                icon: 'none'
              })
              this.getOrderList()
            })
          }
        }
      })
    },
    payOrder() {
      this.userinfo = uni.getStorageSync('userinfo')
      console.log(this.info, this.userinfo);
      uni.showLoading({
        title: '购买中...',
        mask: true
      })

      payOrderWithWXPay({
          orderId:this.info.orderId,
          courseId: this.info.orderId.courseId,
          openId: this.userinfo.wechatOpenid
        }).then(res => {
          // return
          let payData = {
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.packageValue,
            signType: res.data.signType,
            paySign: res.data.paySign,
            appId: res.data.appId,
            // orderId: this.data.orderId
          }
          uni.requestPayment({
            provider: 'wxpay',
            ...payData,
            success: (res) => {
              uni.hideLoading()
              uni.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 1500,
                success: () => {
                  uni.redirectTo({
                    url: '/pages/order/orderPay?orderId=' + this.info.orderId
                  })
                }
              })

            },
            fail: (err) => {
              uni.hideLoading()
              uni.showToast({
                title: '支付失败',
                icon: 'error'
              })
            }
          })
        })
      // uni.navigateTo({
      //   url: `/pages/order/index?orderId=${this.info.orderId}?id=${this.info.courseId}`
      // })
    },
    refund() {
      this.refundForm = {
        orderId: this.info.orderId,
        refundAmount: this.info.totalAmount,
        remark: ''
      }
      this.$refs.showRefundPopup.open()
    },
    // 更新倒计时
    updateCountdown() {
      const now = new Date().getTime()
      const diff = this.info.timeOut - now
      
      if (diff <= 0) {
        this.countdown = {
          text: '已超时',
          isNearTimeout: true
        }
        this.isTimeout = true
        clearInterval(this.timer)
      } else {
        const minutes = Math.floor(diff / 1000 / 60)
        const seconds = Math.floor((diff / 1000) % 60)
        
        this.countdown = {
          text: `${minutes}分${seconds < 10 ? '0' : ''}${seconds}秒`,
          isNearTimeout: minutes < 5
        }
      }
    },
    
    // 启动倒计时
    startCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      
      // 立即执行一次
      this.updateCountdown()
      
      // 每秒更新
      this.timer = setInterval(() => {
        this.updateCountdown()
      }, 1000)
    },
    
    async loadData() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      
      try {
        const res = await getOrderDetail({
          orderId: this.info.orderId
        })
        uni.hideLoading()
        this.info = res.data
        this.startCountdown()
      } catch(err) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 关闭退款弹窗
    closeRefundPopup() {
      this.showRefundPopup = false
      this.refundForm.remark = ''
    },
    
    // 提交退款申请
    submitRefund() {
      this.$refs.refundForm.validate().then(valid => {
        if (valid) {
          // 调用退款接口
          orderRefund(this.refundForm).then(res => {
            uni.showToast({
              title: '退款申请提交成功',
              icon: 'none'
            })
            this.$refs.showRefundPopup.close()
            // 刷新订单详情
            this.loadData()
          }).catch(err => {
            uni.showToast({
              title: err.message || '退款申请失败',
              icon: 'none'
            })
          })
        }
      })
    }
  },
  
  onLoad(options) {
    this.info.orderId = options.orderId
    this.loadData()
  },
  
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
	page {
    background: linear-gradient(180deg, #fc3826FF, #f49d95FF);
		background-size: 100% 450rpx;
		background-repeat: no-repeat;
		background-color: #F7F6F9;
	}

	.order {
		padding-top: 50rpx;
	}

	.order-title {
		font-weight: 400;
		font-size: 36rpx;
		color: #FFFFFF;
		display: block;
		margin-bottom: 20rpx;
		margin-left: 35rpx;
	}

	.order-card {
		background: #FFFFFF;
		box-shadow: 0rpx 9rpx 16rpx 0rpx rgba(137, 135, 142, 0.09);
		border-radius: 10rpx;
		margin: 35rpx;
	}

	.card-info {
		padding: 30rpx;
		display: flex;
		border-bottom: 4rpx solid #F2F2F2FF;

		.card-info-left {
			flex: 1;

			.card-info-title {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.card-info-h1 {
					font-weight: 700;
					font-size: 32rpx;
					color: #12141A;
				}

				.tag {
					margin-left: 25rpx;
					padding: 0 25rpx;
					height: 40rpx;
					line-height: 40rpx;
					background: #FDF7F2;
					border-radius: 4rpx;
					font-weight: 400;
					font-size: 22rpx;
					color: #F47900;
				}
			}

			.card-info-txt {
				font-weight: 400;
				font-size: 26rpx;
				color: #525355;
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				.iconfont {
					margin-right: 5rpx;
					color: #8e929b;
					font-size: 34rpx;
				}
			}
		}

		.price {
			font-weight: 500;
			font-size: 36rpx;
			color: #12141A;
		}
	}

	.sale {
		padding: 30rpx 35rpx;
		font-weight: 500;
		font-size: 26rpx;
		color: #525355;
		display: flex;
		justify-content: space-between;

		.sale-txt {
			text {
				font-weight: 700;
				font-size: 30rpx;
				color: #FD3523;
			}
		}
	}

	.total {
		padding: 0 35rpx 40rpx 35rpx;
		font-weight: 500;
		font-size: 26rpx;
		color: #525355;
		display: flex;
		align-items: baseline;
		justify-content: flex-end;

		.num {
			font-weight: 700;
			font-size: 46rpx;
			color: #FD3523;
		}
	}

	.pay-type {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 35rpx;

		.title {
			font-weight: 700;
			font-size: 32rpx;
			color: #12141A;
		}

		.wechat {
			display: flex;
			align-items: center;
			font-size: 32rpx;

			.iconfont {
				font-size: 56rpx;
				color: #1cab43;
				margin-right: 10rpx;
			}
		}
	}

	.order-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #fff;
		display: flex;
		justify-content: center;
		padding: 15rpx 0;
		align-items: center;

		.btn-pay {
			width: 510rpx;
			height: 85rpx;
			line-height: 85rpx;
			text-align: center;
			background: #FD3523;
			border-radius: 10rpx;
			font-weight: 700;
			font-size: 30rpx;
			color: #FFFFFF;
		}
	}
	.order-card-list{
		font-weight: 400;
		font-size: 26rpx;
		color: #12141A;
		display: flex;
		align-items: center;
		padding-bottom: 30rpx;
		// justify-content: ;
		.first{
			color: #80858F;
		}
	}
  .bottom-btns {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background: #fff;
    display: flex;
    justify-content: flex-end;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    button {
      width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      border-radius: 40rpx;
      margin-left: 20rpx;

      &.btn-cancel {
        color: #666;
        background: #f5f5f5;
      }
      
      &.btn-pay {
        color: #fff;
        background: #FD3523;
      }
    }
  }

.status-box {
  background: linear-gradient(90deg, #FD3523, #FB7A7A);
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  
  .status-header {
    color: #fff;
    
    .status-text {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .countdown {
      margin-top: 20rpx;
      display: flex;
      align-items: center;
      
      .countdown-label {
        font-size: 26rpx;
      }
      
      .countdown-time {
        font-size: 26rpx;
        font-weight: bold;
        
        &.countdown-warning {
          color: #FFE4E4;
        }
      }
    }
  }
}

.refund-popup {
  width: 650rpx;
  background: #fff;
  border-radius: 12rpx;
  
  .popup-header {
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .close {
      font-size: 40rpx;
      color: #999;
      padding: 0 20rpx;
    }
  }
  
  :deep(.uv-form) {
    padding: 30rpx;
    
    .uv-form-item {
      margin-bottom: 20rpx;
      
      &__label {
        width: 160rpx;
        font-size: 28rpx;
        color: #666;
      }
      
      &__content {
        font-size: 28rpx;
        color: #333;
      }
    }
    
    .uv-textarea {
      width: 100%;
      height: 160rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 20rpx;
      font-size: 28rpx;
    }
  }
  
  .popup-footer {
    padding: 30rpx;
    border-top: 1rpx solid #eee;
    display: flex;
    justify-content: flex-end;
    
    button {
      margin-left: 20rpx;
      min-width: 160rpx;
      height: 70rpx;
      line-height: 70rpx;
      font-size: 28rpx;
      border-radius: 35rpx;
      
      &.btn-cancel {
        color: #666;
        background: #f5f5f5;
      }
      
      &.btn-confirm {
        color: #fff;
        background: #FD3523;
      }
    }
  }
}
</style>